package com.zju.iotplant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zju.iotplant.config.RestTemplateUtils;
import com.zju.iotplant.entity.Plant;
import com.zju.iotplant.service.AliRecognize;
import com.zju.iotplant.service.PlantService;
import com.zju.iotplant.util.HttpUtils;
import com.zju.iotplant.util.ResponseResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Yifan Wu
 * Date on 2021/11/4  13:55
 */
@Controller
@ResponseBody
public class PictureController {

    private static final Logger logger = LoggerFactory.getLogger(PictureController.class);

    @Autowired
    private PlantService plantService;

    @RequestMapping("/recognize")
    public ResponseResult<String> recognize(HttpServletRequest request, HttpServletResponse response){
        String pictureUrl = getPictureUrl();
        String plantName = AliRecognize.recognize(pictureUrl);
        return ResponseResult.<String>success(plantName);
    }

    @RequestMapping("/picture")
    public ResponseResult<String> picture(){
        return ResponseResult.<String>success(getPictureUrl());
    }

    @RequestMapping("/detail")
    public Map<String,List> getDetail(){
        String pictureUrl = getPictureUrl();
        String plantName = AliRecognize.recognize(pictureUrl);
        if(plantName == ""){
            logger.warn("API欠费，默认显示山茶花");
            plantName = "山茶花";
        }
        List<Plant> plant = plantService.getByName(plantName);
        Map<String,List> map = new HashMap<>();
        map.put("data",plant);
        return map;
    }

    private String getPictureUrl(){
        String url = "https://images.bemfa.com/cloud/v1/get/?uid=a66566face7a8b360d26fc4bbc5c3bc1&topic=IOT";
        String s = RestTemplateUtils.get(url);
        JSONObject result = JSONObject.parseObject(s);
        JSONArray dataArray = result.getJSONArray("data");
        JSONObject data = dataArray.getJSONObject(0);
        String pictureUrl = data.getString("url");
        logger.info("图片链接{}",pictureUrl);
        return pictureUrl;
    }


}
